import { Injectable, ConflictException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { CreateUserDto } from '../users/dto/create-user.dto';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.usersService.findByUsername(username);
    
    if (!user) {
      return null;
    }
    
    // 检查用户状态
    if (user.status !== 1) {
      return null;
    }
    
    const isPasswordValid = await user.comparePassword(password);
    
    if (isPasswordValid) {
      // 不返回密码
      const { password, ...result } = user.toObject();
      return result;
    }
    
    return null;
  }

  async login(user: any) {
    const payload = { username: user.username, sub: user._id };
    
    // 更新最后登录时间
    await this.usersService.updateLastLoginTime(user._id);
    
    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user._id,
        username: user.username,
        roles: user.roleIds,
      },
    };
  }

  async register(createUserDto: CreateUserDto) {
    try {
      // 创建用户
      return await this.usersService.create(createUserDto);
    } catch (error) {
      if (error.code === 11000) {
        throw new ConflictException('用户名已被占用');
      }
      throw error;
    }
  }
} 